package com.lhz.collector.util;

import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * Created by LHZ on 2016/5/9.
 */
public class ESClientUtil {
    private static final Logger logger = LoggerFactory.getLogger(ESClientUtil.class);
    private ESClientUtil(){}

    public static TransportClient getClient(String clusterName, String nodes){
        Settings settings = Settings.settingsBuilder().put("cluster.name", clusterName)
                .build();
        TransportClient client = TransportClient.builder().settings(settings).build();
        if (nodes != null) {
            String[] arr = nodes.split(",");
            try {
                for (String tmp : arr) {
                    String[] tmpArr = tmp.split(":");
                    if (tmpArr.length == 2) {
                        String host = tmpArr[0];
                        int port = Integer.parseInt(tmpArr[1]);
                        client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(host), port));
                    }
                }
            }catch (UnknownHostException e) {
                logger.error("es error",e);
            }
        }
        return client;
    }

    /*public static TransportClient getClient(String clusterName, String nodes){
        Settings settings = ImmutableSettings.settingsBuilder().put("cluster.name", clusterName)
                .build();
        TransportClient client = new TransportClient(settings);
        if (nodes != null) {
            String[] arr = nodes.split(",");
            for (String tmp : arr) {
                String[] tmpArr = tmp.split(":");
                if(tmpArr.length==2){
                    String host = tmpArr[0];
                    int port = Integer.parseInt(tmpArr[1]);
                    client.addTransportAddress(new InetSocketTransportAddress(host, port));
                }
            }
        }
        return client;
    }*/

}
